<template>
  <div>
    <!-- Header 头部区域 -->
    <div class="search-header">
      <!-- 后退图标 -->
      <van-icon
        name="arrow-left"
        color="white"
        size="18"
        class="goback"
        @click="$router.back()"
      />
      <!-- 搜索组件 -->
      <van-search
        v-model.trim="kw"
        placeholder="请输入搜索关键词"
        background="#007BFF"
        shape="round"
        @input="onInput"
      />
    </div>
    <!-- 搜索建议区域 -->
    <div class="sugg-list" v-if="kw.length != 0">
      <div
        class="sugg-item"
        v-for="(item, i) in suggestList"
        :key="i"
        v-html="item"
        @click="gotoSearchResult"
      ></div>
    </div>
    <div class="search-history" v-else>
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" @click="history = []" />
        </template>
      </van-cell>

      <!-- 历史列表 -->
      <div class="history-list">
        <span
          class="history-item"
          v-for="(tag, i) in history"
          :key="i"
          @click="gotoSearchResult"
          >{{ tag }}</span
        >
      </div>
    </div>
  </div>
</template>

<script>
import { getSuggestListAPI } from '../../api/searchAPI.js'
export default {

  name: 'Search',
  data () {
    return {
      // 搜索关键词
      kw: '',
      timerId: null,
      suggestList: [],
      history: JSON.parse(localStorage.getItem('history') || '[]')
    }
  },

  mounted () {
    const int = document.querySelector('input')
    int.focus()
  },
  methods: {
    onInput () {
      clearTimeout(this.timerId)
      if (this.kw.length === 0) {
        this.suggestList = []
        return
      }
      this.timerId = setTimeout(() => {
        this.initSuggestList()
      }, 500)
    },
    // 请求搜索建议列表数据的方法
    async initSuggestList () {
      // 调用 API 接口
      const { data: res } = await getSuggestListAPI(this.kw)
      if (res.message === 'OK') {
        // 为 suggestList 数据赋值
        this.hlightKeyWords(res.data.options)
        this.suggestList = res.data.options
        const newHistory = this.history.filter(item => item !== this.kw)
        newHistory.unshift(this.kw)
        this.history = newHistory
      }
    },
    gotoSearchResult (e) {
      // e.Target表示当前点击的元素
      // e.currentTarget表示正在触发的当前元素
      this.$router.push('/search/' + e.currentTarget.innerText)
    },

    hlightKeyWords (arr) {
      const reg = new RegExp(this.kw, 'ig')
      arr.forEach((item, i) => {
        arr[i] = item.replace(reg, function (val) {
          return `<span style="color:red;font-weight:bold;">${val}</span>`
        })
      })
    }

  },
  watch: {
    history (newval) {
      localStorage.setItem('history', JSON.stringify(newval))
    }
  }

}
</script>

<style lang="less" scoped>
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
.search-header {
  height: 46px;
  display: flex;
  align-items: center;
  background-color: #007bff;
  overflow: hidden;
  // 后退按钮
  .goback {
    padding-left: 14px;
  }
  // 搜索组件
  .van-search {
    flex: 1;
  }
}
</style>
